"""
强弱因子
强弱 （固定周期的该合约涨幅减同样周期的文华相应指数的涨幅）（归一化处理 ）
一分钟 X分别取值 10 20 40  80   160
数学公式：x分钟的该合约的涨幅（如果跌则为负）减去同样时间段的文华相应指数的涨幅
- 化工和工业品，属于化工的品种优化取化工
- 要按实际品种的交易时间来取指数数据
- 细节：
- 两个指数的数据用一个csv存到一起即可，方便使用
- 取品种主力：第一天主力时间到最后一天主力时间中间的数据
"""

import pandas as pd
import rqdatac as rq
from datetime import datetime, timedelta
from ..utility import make_domaint_time_dict, sec_to_wh_ind


def read_index_data():
    ind_data = pd.read_csv("D:\daily work\ml\wh_index_data.csv")
    ind_data["datetime"] = pd.to_datetime(ind_data["datetime"])
    ind_data.set_index("datetime", inplace=True)
    return ind_data


def _s2_calc_factor(ind_data, domaint_time_dict):
    symbols = list(domaint_time_dict.keys())
    symbols.sort()
    factor_dfs = {}
    for symbol in symbols:
        print(symbol)
        symbol_time = domaint_time_dict[symbol]
        symbol_prices = rq.get_price(symbol, start_date=symbol_time["start"], end_date=symbol_time["last"], frequency="1m",
                                   fields="close", expect_df=False)
        symbol_prices.index -= timedelta(minutes=1)
        factor_qr = pd.DataFrame()
        price_df = pd.DataFrame({symbol: symbol_prices, "wh_ind": ind_data})
        price_df.dropna(inplace=True)
        for window in [10, 20, 40, 80, 160]:
            price_shift = price_df.shift(window)
            r1 = (price_df - price_shift) / price_shift
            factor_qr[f"r{window}"] = r1[symbol] - r1["wh_ind"]
        factor_qr["symbol"] = symbol
        factor_dfs[symbol] = factor_qr
    return factor_dfs


def get_factor_df(sec_id, prices):
    print(__file__)
    ind_data = pd.read_csv("D:\daily work\ml\wh_index_data.csv")
    ind_data["datetime"] = pd.to_datetime(ind_data["datetime"])
    ind_data.set_index("datetime", inplace=True)
    wh_ind = sec_to_wh_ind.get(sec_id, "whgy")
    prices["wh_ind"] = ind_data[wh_ind]
    #price_df.dropna(inplace=True)
    for window in [10, 20, 40, 80, 160]:
        price_shift = prices["close"].shift(window)
        ind_shift = prices["wh_ind"].shift(window)
        r1 = (prices["close"] - price_shift) / price_shift
        ind_r = (prices["wh_ind"] - ind_shift) / ind_shift
        prices[f"qr_{window}"] = r1 - ind_r
    return prices


if __name__ == "__main__":
    if not rq.initialized():
        rq.init("13570866213", "39314656")
    sec_id = "i"
    ind_name = "whgy"
    ind_data = read_index_data()
    domaint_time_dict = make_domaint_time_dict(sec_id.upper())
    dfs = _s2_calc_factor(ind_data[ind_name], domaint_time_dict)
    result_df = pd.concat(list(dfs.values()))

